<template>
  <div id="register">
    <div class="reg-title">注册账号</div>
    <div class="reg-sub-title">
      注：新用户注册，<span class="c-red">*</span>号为必填项
    </div>
    <div class="reg-main">
      <el-form :model="form">
        <el-form-item label="*姓名">
          <span slot="label"><span class="c-red">*</span>姓名</span>
          <el-input maxlength="30" v-model="formAdd.name" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="*账号">
          <span slot="label"><span class="c-red">*</span>账号</span>
          <el-input
            maxlength="20"
            v-model="formAdd.account"
            placeholder="请输入"
          ></el-input>
          注：建议用手机号，将作为讲师登录账号使用，默认密码000000
        </el-form-item>
        <el-form-item label="电话">
          <span slot="label"><span class="c-red">*</span>电话</span>
          <el-input v-model="formAdd.phone" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="证件照">
          <span slot="label"><span class="c-red">*</span>证件照</span>
          <el-upload
            class="avatar-uploader"
            action="/lec/resource/upload?type=1"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            accept=".jpg,.jpeg,.JPG,.JPEG"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <div>
            <h3>请上传二寸照片</h3>
            只能上传jpg文件，尺寸为200px*200px，且不超过10M
          </div>
        </el-form-item>
        <el-form-item label="性别">
          <span slot="label"><span class="c-red">*</span>性别</span>
          <el-select v-model="formAdd.sex" placeholder="请选择">
            <el-option
              v-for="val in local.sexOption"
              :key="val.id"
              :value="val.id"
              :label="val.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="年龄">
          <span slot="label"><span class="c-red">*</span>年龄</span>
          <el-input v-model="formAdd.age" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="省份">
          <span slot="label"><span class="c-red">*</span>省份</span>
          <el-select v-model="formAdd.province" placeholder="请选择">
            <el-option
              v-for="(val, index) in local.provinceOption"
              :key="index"
              :value="val"
              :label="val"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="机构">
          <span slot="label"><span class="c-red">*</span>机构</span>
          <casader :pid="formAdd.org" ref="dialogChild"></casader>
        </el-form-item>
        <el-form-item label="职务">
          <span slot="label"><span class="c-red">*</span>职务</span>
          <el-input v-model="formAdd.profession" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="单位">
          <span slot="label"><span class="c-red">*</span>单位</span>
          <el-input v-model="formAdd.department" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="讲师类型">
          <span slot="label"><span class="c-red">*</span>讲师类型</span>
          <el-cascader
            v-model="formAdd.types"
            :options="local.teacherOptions"
            :props="props"
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="宣讲方向">
          <span slot="label"><span class="c-red">*</span>宣讲方向</span>
          <el-input v-model="formAdd.direction" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="简介">
          <el-input
            type="textarea"
            :rows="4"
            v-model="formAdd.description"
            placeholder="请输入"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <div class="reg-btn-group">
        <el-button @click="saveAdd(1)" class="reg-btn">保存</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import Casader from "../components/cascaderD";
export default {
  components: { Casader },
  data() {
    return {
      props: { multiple: true },
      dateValue: [],
      pid: "",
      //弹框是否为修改
      isEdit: false,
      imageUrl: "",
      //是否读取完pid
      isPid: false,
      //删除数组
      ids: [],
      //添加
      dialogAdd: false,
      form: {
        phone: "",
        pid: 0,
        count: "",
      },
      //添加列表
      formAdd: {
        types: [],
        count: "",
        name: "",
        head: "",
        sex: "",
        age: "",
        phone: "",
        account: "",
        province: "",
        profession: "",
        org: 0,
        department: "",
        direction: "",
        description: "",
      },
      local: {
        teacherOptions: [],
        //弹框信息
        dialogInfo: {
          name: "添加讲师",
          isAdd: true,
        },
        sexOption: [
          {
            id: 1,
            name: "男",
          },
          {
            id: 2,
            name: "女",
          },
        ],
        provinceOption: [
          "北京市",
          "浙江省",
          "天津市",
          "安徽省",
          "上海市",
          "福建省",
          "重庆市",
          "江西省",
          "山东省",
          "河南省",
          "湖北省",
          "湖南省",
          "广东省",
          "海南省",
          "山西省",
          "青海省",
          "江苏省",
          "辽宁省",
          "吉林省",
          "台湾省",
          "河北省",
          "贵州省",
          "四川省",
          "云南省",
          "陕西省",
          "甘肃省",
          "黑龙江省",
          "香港特别行政区",
          "澳门特别行政区",
          "广西壮族自治区",
          "宁夏回族自治区",
          "新疆维吾尔自治区",
          "内蒙古自治区",
          "西藏自治区",
        ],
        teacherDetails: {
          id: "",
          name: "",
          head: {
            fullUrl: "",
            shortUrl: "",
          },
          sex: "",
          age: "",
          phone: "",
          account: "",
          path: [1],
          province: "",
          profession: "",
          direction: "",
          description: "",
        },
      },
      //权限列表
      roleOption: [],
      //修改
      dialogEdit: false,
      currentPage: 1,
      pageSize: 10,
      totalCount: 1000,
      tableData: [
        {
          name: "张三",
        },
      ],
      aid: 0,
    };
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      //this.getPid();
      this.getTeacherTypes();
    },
    uploadTeaSuccess(res) {
      this.$message.success(res.message);
    },
    uploadTeaError(res) {
      this.$message.error(res.message);
    },
    //下载模板
    downLoadsModel() {
      let self = this;
      const loading = self.$loading({
        lock: true,
        text: "加载中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      self.$http
        .get(`/teacher/templateDownload`, { responseType: "blob" })
        .then((response) => {
          let blob = new Blob([response.data], {
            type: response.headers["content-disposition"],
          });
          //console.log(response.headers['content-disposition'],55555);
          let fileName = "讲师导入模板.xlsx";
          let url = window.URL.createObjectURL(blob);
          let downloadElement = document.createElement("a");
          downloadElement.style.display = "none";
          downloadElement.href = url;
          downloadElement.download = fileName; //下载后文件名
          document.body.appendChild(downloadElement);
          downloadElement.click(); //点击下载
          document.body.removeChild(downloadElement); //下载完成移除元素
          window.URL.revokeObjectURL(url);
          loading.close();
          console.log(1234);
        })
        .catch((err) => {
          console.log(err);
          loading.close();
        });
    },
    //讲师类型改变
    handleChange(value) {
      console.log(value);
    },
    //获取讲师类型
    getTeacherTypes() {
      this.$http.get(`/teacher/types`).then((response) => {
        let res = response.data;
        if (res.code == "200") {
          console.log(res, 1666666);
          this.local.teacherOptions = res.data;
        } else {
          this.$message.error(res.message);
        }
      });
    },
    //清空
    emptyForm() {
      this.form.phone = "";
      this.form.count = "";
      this.$refs.child.changeValue([]);
      console.log(this.form.pid);
      this.dateValue = [];
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.formAdd.head = res.data;
      console.log(this.imageUrl, 234);
      console.log(this.formAdd.head, 2234);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 10;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 10MB!");
      }
      return isJPG && isLt2M;
    },
    //添加修改保存
    saveAdd(type) {
      let self = this;
      let pid = self.$refs.dialogChild.cx();
      if (pid !== 0) {
        self.formAdd.org = pid;
      } else {
        self.formAdd.org = "";
      }
      let url = "";
      //修改
      if (type === 1) {
        // url = "/teacher/add";
        url = "/teacher/register";
      }
      //修改
      if (type === 2) {
        url = "/teacher/update";
      }
      self.$http
        .post(url, self.formAdd)
        .then((response) => {
          let res = response.data;
          if (res.code == "200") {
            self.$message.success("注册成功");
            // self.dialogAdd = false;
            // self.getList();
            self.$router.push("login");
          } else {
            self.$message.error(res.message);
          }
        })
        .catch((err) => {
          self.$message.error(err.message);
        });
    },
    //关闭
    close() {
      this.imageUrl = "";
      this.formAdd = {
        types: [],
        count: "",
        name: "",
        head: "",
        sex: "",
        age: "",
        phone: "",
        account: "",
        province: "",
        profession: "",
        org: "",
        department: "",
        direction: "",
        description: "",
      };
      this.$refs.dialogChild.changeValue([]);
      this.formAdd.org = this.pid;
    },
    //添加讲师弹窗
    addTeacher() {
      this.formAdd.org = this.pid;
      this.local.dialogInfo.title = "添加讲师";
      this.local.dialogInfo.isAdd = true;
      this.dialogAdd = true;
    },
    //查看详情
    showDetails(id) {
      let self = this;
      self.local.dialogInfo.title = "修改";
      self.local.dialogInfo.isAdd = false;
      self.dialogAdd = true;
      self.$http
        .get(`/teacher/info?id=${id}`)
        .then((response) => {
          let res = response.data;
          if (res.code == "200") {
            self.formAdd = res.data;
            self.imageUrl = res.data.head.fullUrl;
            self.formAdd.head = res.data.head.shortUrl;
            self.formAdd.org = self.pid;
            let av = res.data.path;
            self.$nextTick(function () {
              self.$refs.dialogChild.changeValue(av);
            });
          } else {
            self.$message.error(res.message);
          }
        })
        .catch((err) => {
          self.$message.error(err.message);
        });
    },
    rowpassword(id) {
      let self = this;
      self.$http.post(`/teacher/reset?id=${id}`).then((response) => {
        let res = response.data;
        if (res.code == "200") {
          self.$message.success(res.message);
        } else {
          self.$message.error(res.message);
        }
      });
    },
    //获取pid
    getPid() {
      let self = this;
      self.$http.get("/admin/pid").then((response) => {
        let res = response.data;
        if (res.code == "200") {
          console.log(res, 111222);
          self.isPid = true;
          self.pid = res.data;
          self.form.pid = res.data;
          self.formAdd.org = self.pid;
          console.log(self.form.pid, 2222222);
          self.$nextTick(function () {
            self.getList();
          });
        } else {
          self.$message.error(res.message);
        }
      });
    },
    //获取权限列表
    getRole() {
      let self = this;
      self.$http.get("/admin/role").then((response) => {
        let res = response.data;
        if (res.code == "200") {
          console.log(res, 111222);
          self.roleOption = res.data;
        } else {
          self.$message.error(res.message);
        }
      });
    },
    //获取列表
    getList() {
      let self = this;
      let pid = self.$refs.child.cx();
      console.log(pid, 212);
      let startTime = "";
      let endTime = "";
      console.log(self.dateValue, 222222);
      if (self.dateValue && self.dateValue.length) {
        startTime = self.dateValue[0];
        endTime = self.dateValue[1];
      }
      self.$http
        .post(`/teacher/list`, {
          count: self.form.count, //总数
          endTime: endTime, //结束时间
          org: pid, //机构
          pageNum: self.currentPage,
          pageSize: self.pageSize,
          phone: self.form.phone, //手机号码
          startTime: startTime, //开始时间
        })
        .then((response) => {
          let res = response.data;
          if (res.code == "200") {
            console.log(res, 1);
            self.tableData = res.data.content;
            self.totalCount = res.data.total;
            console.log(self.tableData, 111);
          } else {
            self.$message.error(res.message);
          }
        });
    },
    handleSelectionChange(rows) {
      console.log(rows, 1111);
      this.ids = rows.map((item) => item.id);
    },
    //查询
    onSubmit() {
      this.currentPage = 1;
      this.getList();
    },
    //下载
    downLoads() {
      let self = this;
      let pid = self.$refs.child.cx();
      const loading = self.$loading({
        lock: true,
        text: "加载中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      self.$http
        .get(`/teacher/download?id=${pid}`, { responseType: "blob" })
        .then((response) => {
          let blob = new Blob([response.data], {
            type: response.headers["content-disposition"],
          });
          //console.log(response.headers['content-disposition'],55555);
          let fileName = "讲师列表.xlsx";
          let url = window.URL.createObjectURL(blob);
          let downloadElement = document.createElement("a");
          downloadElement.style.display = "none";
          downloadElement.href = url;
          downloadElement.download = fileName; //下载后文件名
          document.body.appendChild(downloadElement);
          downloadElement.click(); //点击下载
          document.body.removeChild(downloadElement); //下载完成移除元素
          window.URL.revokeObjectURL(url);
          loading.close();
          console.log(1234);
        })
        .catch((err) => {
          console.log(err);
          loading.close();
        });
    },
    //分页
    handleSizeChange: function (size) {
      this.pageSize = size;
    },
    handleCurrentChange: function (currentPage) {
      this.currentPage = currentPage;
      this.getList();
    },

    //批量删除
    deleteAll() {
      let self = this;
      let ids = self.ids;
      console.log(ids, 1122);
      if (!ids.length) {
        self.$message.error("请选择要删除的数据");
        return;
      }
      self
        .$confirm("是否删除选中?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then(() => {
          self.$http.post("/teacher/delete", ids).then(
            (response) => {
              let res = response.data;
              if (res.code == "200") {
                self.$message.success("删除成功");
                self.ids = [];
                self.currentPage = 1;
                self.getList();
              } else {
                self.$message.error(res.message);
              }
            },
            (err) => {
              console.log("err");
            }
          );
        })
        .catch(() => {});
    },
  },
};
</script>

<style lang="scss">
#register {
  margin: 0 auto;
  padding: 50px 85px;
  .c-red {
    color: red;
  }
  .reg-title {
    height: 30px;
    font-size: 30px;
    line-height: 30px;
    font-family: Microsoft YaHei;
    font-weight: 400;
    color: #2d2d2d;
    text-align: center;
    margin-bottom: 30px;
  }
  .reg-sub-title {
    height: 15px;
    font-size: 14px;
    font-family: Microsoft YaHei;
    font-weight: 400;
    color: #2d2d2d;
    text-align: center;
  }
  .reg-main {
    width: 50%;
    margin: 0 auto;
    padding: 45px 0;
    .el-form-item {
      .el-form-item__label {
        width: 80px;
        font-size: 14px;
      }
      .el-form-item__content {
        float: left;
        width: calc(100% - 80px);
        .el-input,
        .el-select,
        .el-cascader {
          width: 100%;
        }
      }
    }
    .reg-btn-group {
      margin-top: 30px;
      text-align: center;
      .reg-btn {
        background: #2f71a9;
        color: #fff;
      }
    }
  }
  .el-input {
    width: auto;
  }
  .add-dialog {
    .el-cascader {
      width: auto !important;
    }
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>
